const vscode = require('vscode');
const path = require('path');
const loginWebview = require('../view/setting/loginWebview');
const AccountClass = require('../util/accountClass');
const hiSmartLiteEx = require('../hiSmartLiteEx');
const LoginClass = require('../view/setting/loginClass');

class CommonApi {
  constructor(context) {
    this.context = context;
  }

  loginCommands() {
    const accountClass = new AccountClass();
    const loginClass = new LoginClass();
    return [
      vscode.commands.registerCommand('HiSmartLiteFoundation.redirectLoginInfo', () => {
        accountClass.redirectLoginInfo();
      }),
      vscode.commands.registerCommand('HiSmartLiteFoundation.cleanAccountInfo', () => {
        accountClass.clearAccountData();
      }),
      vscode.commands.registerCommand('HiSmartLiteFoundation.openLoginWebview', () => {
        loginWebview.createPanel();
      }),
      vscode.commands.registerCommand('HiSmartLiteFoundation.getGiteeLoginInfo', () => {
        return accountClass.getGiteeLoginInfo();
      }),
      vscode.commands.registerCommand('HiSmartLiteFoundation.getAccessToken', () => {
        return loginClass.getAccessToken();
      }),
      vscode.commands.registerCommand('HiSmartLiteFoundation.refreshAccessToken', () => {
        return loginClass.refreshAccessToken();
      }),
      // 子插件向基座插件注册配置项
      vscode.commands.registerCommand('HiSmartLiteFoundation.registerChildExtension', () => {
        this.registerChildExtension();
      }),
    ];
  }

  registerChildExtension(currentChildExtension) {
    if (currentChildExtension) {
      let tempPlugin = hiSmartLiteEx.childStaticExtensions.filter(t => {
        return t.pluginId === currentChildExtension.pluginId;
      });
      if (tempPlugin.length === 0) {
        hiSmartLiteEx.childStaticExtensions.push(currentChildExtension);
        const childExtension = vscode.extensions.getExtension(currentChildExtension.pluginId);
        if (childExtension) {
          hiSmartLiteEx.localResourceRoots.push(vscode.Uri.file(path.join(childExtension.extensionPath, 'media')));
        }
      }
    }
  }

  register() {
    this.context.subscriptions.push(
      ...this.loginCommands(),
    );
  }
}

module.exports = CommonApi;